package com.touzbi.hss.bo;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.touzbi.hss.beans.Patient;
import com.touzbi.hss.dao.AbstractDAOFactory;
import com.touzbi.hss.dao.AbstractPatientDAO;
import com.touzbi.hss.pagemanager.AbstractPageManager;
import com.touzbi.hss.parametermanager.AbstractParameterManager;

public class SearchBO implements AbstractSearchBO {

	private static final String QUERY_PARAM = "q";
	private static final int MIN_LENGTH = 3;
	private static final String EXCEPTION_QUERY_TOO_SHORT = "Query too short, please enter at least "
			+ MIN_LENGTH + " characters";

	private AbstractPatientDAO patientDAO;
	private AbstractPageManager pageManager;
	private AbstractParameterManager paramManager;
	private String error = null;

	public SearchBO(AbstractDAOFactory daoFactory,
			AbstractPageManager pageManager,
			AbstractParameterManager paramManager, HttpServletRequest req) {
		this.patientDAO = daoFactory.getPatientDAO();
		this.pageManager = pageManager;
		this.paramManager = paramManager;
	}

	// XXX Need of query validator
	private String getQueryParam() throws Exception {
		String query = this.paramManager.getParamValue(QUERY_PARAM);
		if (query != null && query.length() >= MIN_LENGTH) {
			return query;
		} else {
			throw new Exception(EXCEPTION_QUERY_TOO_SHORT);
		}
	}

	private List<Patient> getQueryResult() {
		String query = null;
		List<Patient> patients = null;
		int count = this.pageManager.getPageSize();
		int pageNumber = this.pageManager.getPageNumber();
		try {
			query = getQueryParam();
			patients = this.patientDAO.getQueryResult(query,
					pageNumber * count, count);
		} catch (Exception e) {
			this.error = e.getMessage();
		}

		return patients;
	}

	public long getQueryCount() {
		try {
			return this.patientDAO.getPatientCount(getQueryParam());
		} catch (Exception e) {
			this.error = e.getMessage();
			return 0;
		}
	}

	@Override
	public List<Patient> search() {
		return getQueryResult();
	}

	public String getError() {
		return this.error;
	}

}
